package com.hyg.lib_common.loginpart;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.R;
import com.hyg.lib_common.WebView.WebViewActivity;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;
@Route(path = Constants.PATH_ACTIVITY_MODULE_USER_REGISTER)
public class RegisterActivity extends BaseActivity {

    protected void onStop(){
        super.onStop();
        if(this.isFinishing()){
            myHandler.removeCallbacksAndMessages(null);
        }
    }

    private Button bt_register;
    private ImageView back;
    private EditText et_code, et_phone, et_pass, et_name;
    private ToggleButton togglePwd;
    private Button getcode, forget;
    private TextView timertext;
    private String code = "";
    private String phone = "";
    private String password = "";
    public String mphone = "[1][3456789]\\d{9}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mcode = "\\d{4,6}";//第一位是数字1，第二位是358中的一个在加上9个数字
    public String mpassword = "[A-Za-z0-9]{6,18}";//第一位是字母，后面加上4-15个

    private CheckBox CB_Agreement;
    private TextView Agreement;

    private Timer mTimer = null;
    private int countdowns = 3;

    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private RegisterActivity activity;
        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (RegisterActivity) reference.get();
        }

        @SuppressLint("NewApi")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://注册
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
//                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadLogin", jsondata + "");
                        if (status.equals("200")) {
                            JSONObject data = new JSONObject(jsondata.getString("data"));
                            activity.editorn = activity.sn.edit();
                            activity.editorn.putString("phone", activity.phone);
                            activity.editorn.putString("password", activity.password);
                            activity.editorn.putString("token", data.getString("token"));
                            activity.editorn.commit();

                            activity.dialogShow();
                        } else {
                            if (null != jsondata.getString("data") && !jsondata.getString("data").equals("null") && !jsondata.getString("data").equals("")) {
                                JSONObject data = new JSONObject(jsondata.getString("data"));
                                String messages = data.getString("message");
                                if (activity.pDialog.isShowing())
                                    activity.pDialog.dismiss();
                                activity.pDialog = new SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE);
                                activity.pDialog.setTitleText(messages);
                                activity.pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismiss();
                                    }
                                });
                                activity.pDialog.show();
                            } else {
                                if (activity.pDialog.isShowing())activity.pDialog.dismiss();
//                                activity.ErrorDialog(message);
                            }
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
                case 2://获取注册验证码
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String success = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadLogin", jsondata + "");
                        if (success.equals("200")) {
                            if (!Utils.isEmpty(message)) {
                                Toast.makeText(activity,message, Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            if (activity.pDialog.isShowing())activity.pDialog.dismiss();
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
                case 3://用手机号和验证码登录
                    try {
                        //{"code":200,"message":"操作成功","data":{"code":500,"message":null,"data":{"message":"该手机号没有注册","status":1}}}
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
//                        Log.d("welcomeadLogin", jsondata + "");
                        if (status.equals("200")) {
                            JSONObject data = new JSONObject(jsondata.getString("data"));
                            if(data.getString("code").equals("200")){
                                JSONObject datas = new JSONObject(data.getString("data"));
                                activity.editorn = activity.sn.edit();
                                activity.editorn.putString("phone", activity.phone);
                                activity.editorn.putString("password", activity.password);
                                activity.editorn.putString("token", datas.getString("token"));
                                activity.editorn.commit();
                                activity.JUMPActivity();

                            }else{
                                String messages = data.getString("message");
                                String ErrorStatus = data.getString("status");
                                if (ErrorStatus.equals("1")) {
                                    if (activity.pDialog.isShowing())
                                        activity.pDialog.dismiss();
                                    activity.pDialog = new SweetAlertDialog(activity, SweetAlertDialog.ERROR_TYPE);
                                    activity.pDialog.setTitleText(messages);
                                    activity.pDialog.setCancelable(false);
                                    activity.pDialog.setConfirmButton("去注册", new SweetAlertDialog.OnSweetClickListener() {
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismiss();
                                        }
                                    });
                                    activity.pDialog.show();
                                } else {
                                    if (activity.pDialog.isShowing())activity.pDialog.dismiss();
                                    activity.ErrorDialog(messages);
                                }
                            }
                        } else {
                            if (activity.pDialog.isShowing())activity.pDialog.dismiss();
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
                case 100:   //提示倒计时可 点击获取验证码
                    activity.getcode.setText(activity.countdown + "s后可获取");
                    activity.getcode.setAlpha(0.5f);
                    if (0 == activity.countdown) {
                        //停止倒计时显示页面
                        activity.resume();
                        activity.stopmTimer();
                        return;
                    }
                    activity.countdown--;
                    break;
                case 101:   //提示倒计时进入登录页面
                    activity.timertext.setText(activity.countdowns + "");
                    if (0 == activity.countdowns) {
                        //停止倒计时显示页面
                        activity.stopTimer();
                        if (activity.pDialog.isShowing()) {
                            activity.pDialog.dismiss();
                        }
                        activity.JUMPActivity();
                        //停止倒计时显示页面
                        return;
                    }
                    if (activity.pDialog.isShowing()) {
                        activity.countdowns--;
                    }
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.white),00,null,null,true);
        init();
    }

    Timer timer = new Timer();
    public void dialogShow() {
        if (pDialog.isShowing())
            pDialog.dismiss();
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater = LayoutInflater.from(RegisterActivity.this);
        View view = inflater.inflate(R.layout.dialog_layouts, null);
        timertext = view.findViewById(R.id.tv_dialog);
        timertext.setGravity(Gravity.CENTER);
        TimerTask timerTask = new TimerTask() {
            public void run() {
                myHandler.sendEmptyMessage(101);
            }
        };

        pDialog = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.SUCCESS_TYPE);
        pDialog.setTitleText("注册成功，即将帮您自动登录");
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("直接登录", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                stopTimer();
                pDialog.dismiss();
                JUMPActivity();
            }
        });
        pDialog.show();
        timer.schedule(timerTask, 500, 1000);
    }

    public void JUMPActivity(){
        countdowns--;
//        Intent intent = new Intent(RegisterActivity.this, MainView.class);
////        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        // 如果要被开启的activity已经在当前的task中运行，系统不会生成该activity的一个新的实例，在该栈顶部的所有其他的activity会被销毁，这个intent通过 onNewIntent()被传递给该重新运行的activity的实例（现在在栈顶部）。
//        startActivity(intent);// 跳转

        ToIntent(Constants.PATH_ACTIVITY_MAIN, true);
        finish();
        overridePendingTransition(R.anim.fade, R.anim.hold);
    }

    public void init() {
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                RegisterActivity.this.finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });

        bt_register = (Button) findViewById(R.id.bt_register);
        getcode = (Button) findViewById(R.id.getcode);
        et_code = (EditText) findViewById(R.id.et_code);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_pass = (EditText) findViewById(R.id.et_password);
        CB_Agreement = (CheckBox) findViewById(R.id.CB_Agreement);
        CB_Agreement.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setIsCheckAgreement();
            }
        });
        Agreement = (TextView) findViewById(R.id.Agreement);
        togglePwd = (ToggleButton) findViewById(R.id.togglePwd);
        togglePwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) { //如果选中，显示密码
                    et_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else { //否则隐藏密码
                    et_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });

        Agreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        Agreement.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                Intent it = new Intent(RegisterActivity.this, WebViewActivity.class);
                it.putExtra("url", UrlUtils.PrivacyUrl);
                it.putExtra("title","隐私政策与免责声明");
                it.putExtra("type","Privacy");
                startActivity(it);

            }
        });
        setIsCheckAgreement();
        Intent it = getIntent();
        if (null != it.getStringExtra("phone") && !it.getStringExtra("phone").equals("")) {
            et_phone.setText(it.getStringExtra("phone"));
        }
        if (null != it.getStringExtra("code") && !it.getStringExtra("code").equals("")) {
            et_code.setText(it.getStringExtra("code"));
        }

        bt_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
//                dialogShow();
                phone = et_phone.getText().toString();
                password = et_pass.getText().toString();
                code = et_code.getText().toString();

                if (phone.equals("")) {
                    dialog("请填写手机号");
                } else if (password.equals("")) {
                    dialog("请填写密码");
                } else if (code.equals("")) {
                    dialog("请填写验证码");
                } else {
                    if (!phone.matches(mphone)) {
                        dialog("手机号格式错误，请重新输入");
                    } else if (!password.matches(mpassword)) {
                        dialog("密码格式不对或者包含非格式字符，请重新输入。");
                        et_pass.setText("");
                    } else if (!code.matches(mcode)) {
                        dialog("验证码格式错误，请重新输入。");
                    } else {
                        String str_tag = "1";
                        FormBody formBody = new FormBody.Builder()
                                .add("phone", phone)//设置参数名称和参数值
                                .add("password", password)//设置参数名称和参数值
                                .add("smsCode", code)//设置参数名称和参数值
                                .build();
                        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.regisiterAddr);

                        if (pDialog.isShowing())
                            pDialog.dismiss();
                        View view = View.inflate(RegisterActivity.this, R.layout.dialog_loading, null);
                        TextView loadingText = (TextView) view.findViewById(R.id.loadingText);
                        loadingText.setText("正在注册中...");
                        pDialog = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.NORMAL_TYPE);
                        pDialog.setCustomView(view);
                        pDialog.setConfirmButton("好的", new SweetAlertDialog.OnSweetClickListener() {
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        });
                        pDialog.show();
                    }
                }
            }
        });

        getcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = et_phone.getText().toString();
                if (Utils.isFastClick()) {
                    return;
                }
                if (phone.equals("")) {
                    dialog("电话号码不可为空，请填写电话号码。");
                } else if (!phone.matches(mphone)) {
                    dialog("电话号码格式不对，请重新输入。");
                    et_phone.setText("");
                } else {
                    et_code.setHint("请注意查看短信");
                    startTimer();
                    String str_tag = "2";
                    FormBody formBody = new FormBody.Builder()
                            .add("phone", phone)//设置参数名称和参数值
                            .build();
                    sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.codeaddr);
                }
            }
        });
    }

    public void setIsCheckAgreement(){
        /*检测条款是否选上*/
        if (CB_Agreement.isChecked()) {
            CB_Agreement.setChecked(true);
            bt_register.setClickable(true);
        } else {
            CB_Agreement.setChecked(false);
            bt_register.setClickable(false);

            if (pDialog.isShowing())
                pDialog.dismiss();
            pDialog = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.WARNING_TYPE);
            pDialog.setTitleText("提示");
            pDialog.setContentText("注册账号须请您接受\n《隐私政策和免责声明》");
            pDialog.setConfirmButton("我同意", new SweetAlertDialog.OnSweetClickListener() {
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                    CB_Agreement.setChecked(true);
                }
            });
            pDialog.show();
        }
    }

    public void dialog(String text) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        pDialog = new SweetAlertDialog(RegisterActivity.this, SweetAlertDialog.ERROR_TYPE);
        pDialog.setTitleText("格式错误");
        pDialog.setContentText(text);
        pDialog.setConfirmButton("知道啦", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
        pDialog.show();
    }

    public void AutoLogin(String username, String pwd) {
        String str_tag = "3";
        FormBody formBody = new FormBody.Builder()
                .add("phone", username)//设置参数名称和参数值
                .add("password", pwd)//设置参数名称和参数值
                .build();
        sendPostNetwork(str_tag, formBody, myHandler, UrlUtils.loginPwdAddr);
    }

    //开始倒计时
    private void startTimer() {
        //点击获取验证码后改变按钮的状态,让按钮不可点击
        getcode.setClickable(false);
        if (mTimer == null) {
            mTimer = new Timer(true);
        }
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {

                myHandler.sendEmptyMessage(100);
            }
        }, 0, 1000);
    }

    private int countdown = 60;

    private void resume() {
        stopmTimer();
        countdown = 45;
        //倒计时结束后,让按钮重新可点击
        getcode.setClickable(true);
        getcode.setText("获取验证码");
        getcode.setAlpha(0.9f);
    }

    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
    private void stopmTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }



}
